<template>
  <t-dialog
    v-model:visible="visible"
    header="选择商品"
    width="1000"
    @opened="loadRelations"
  >
    <div class="selector-container">
      <!-- 分类多选 -->
      <div class="category-list">
        <t-checkbox-group v-model="selectedCategoryIds" @change="onCategoryChange">
          <t-checkbox
            v-for="cat in categoryList"
            :key="cat.id"
            :value="cat.id"
          >
            {{ cat.name }}
          </t-checkbox>
        </t-checkbox-group>
      </div>

      <!-- 分类对应的商品列表 -->
      <div
        v-for="cat in visibleCategories"
        :key="cat.id"
        class="category-section"
      >
        <h4 class="category-title">{{ cat.name }}</h4>

        <t-table
          :columns="getColumns(cat.id)"
          :data="commodityMap[cat.id]"
          :row-key="rowKey"
          bordered
          hover
          table-layout="auto"
          :selected-row-keys="selectedCommodityIds[cat.id]"
          @select-change="(keys, ctx) => handleSelectChange(cat.id, keys, ctx)"
        >
          <template #price="{ row }">￥{{ row.price }}</template>
          <template #originalPrice="{ row }">
            <span v-if="row.originalPrice">￥{{ row.originalPrice }}</span>
            <span v-else>-</span>
          </template>
        </t-table>

        <div class="pagination">
          <t-pagination
            :total="commodityPage[cat.id]?.total || 0"
            :page-size="commodityPage[cat.id]?.pageSize || 10"
            :current="commodityPage[cat.id]?.pageNum || 1"
            @change="(p) => onPageChange(cat.id, p)"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <t-space>
        <t-button theme="default" @click="visible = false">取消</t-button>
        <t-button theme="primary" @click="confirmSelect">确定并保存</t-button>
      </t-space>
    </template>
  </t-dialog>
</template>

<script setup>
import { reactive, ref, watch, computed, onMounted } from 'vue'
import CategoryService from '../../api/category'
import CommodityService from '../../api/commodity'
import RelationService from '../../api/pageComponentDataRelation'
import { MessagePlugin } from 'tdesign-vue-next'

const props = defineProps({
  modelValue: Boolean,
  pageId: Number,
  componentId: String
})
const emit = defineEmits(['update:modelValue'])

const visible = ref(props.modelValue)
watch(() => props.modelValue, v => (visible.value = v))
watch(visible, v => emit('update:modelValue', v))

const categoryList = ref([])
const selectedCategoryIds = ref([])
const commodityMap = reactive({})
const selectedCommodityIds = reactive({})
const commodityPage = reactive({})
const rowKey = 'id'

// ---------------------- 列定义 ----------------------
const getColumns = (catId) => [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'id', title: 'ID', width: 60 },
  { colKey: 'title', title: '商品标题', width: 220 },
  { colKey: 'price', title: '价格', width: 100 },
  { colKey: 'originalPrice', title: '原价', width: 100 }
]

// ---------------------- 分类与商品加载 ----------------------
const fetchCategories = async () => {
  try {
    const res = await CategoryService.getPage('', 1, 100)
    categoryList.value = res.data.records || res.data || []
    categoryList.value.forEach(cat => {
      commodityMap[cat.id] = []
      selectedCommodityIds[cat.id] = []
      commodityPage[cat.id] = { pageNum: 1, pageSize: 10, total: 0 }
    })
  } catch (e) {
    console.error(e)
    MessagePlugin.error('获取分类列表失败')
  }
}

const fetchCommodities = async categoryId => {
  try {
    const pageInfo = commodityPage[categoryId]
    const res = await CommodityService.getCommodityPage('', pageInfo.pageNum, pageInfo.pageSize)
    commodityMap[categoryId] = res.data.records || []
    pageInfo.total = res.data.total || 0
  } catch (e) {
    console.error(e)
    MessagePlugin.error('获取商品列表失败')
  }
}

const onCategoryChange = newList => {
  newList.forEach(catId => {
    if (commodityMap[catId]?.length === 0) fetchCommodities(catId)
  })
}

const handleSelectChange = (catId, keys, { selectedRowData }) => {
  selectedCommodityIds[catId] = keys
}

const onPageChange = (categoryId, page) => {
  commodityPage[categoryId].pageNum = page.current
  fetchCommodities(categoryId)
}

const visibleCategories = computed(() =>
  categoryList.value.filter(cat => selectedCategoryIds.value.includes(cat.id))
)

// ---------------------- 加载已有关联数据 ----------------------
const loadRelations = async () => {
  if (!props.pageId || !props.componentId) return
  try {
    const res = await RelationService.getByComponentId(props.componentId)
    console.log(res)
    const list = res.data || []
    if (list.length === 0) return

    // 1. 找出所有已关联的分类
    const categoryIds = [...new Set(list.filter(r => !r.parentId).map(r => r.bizId))]
    selectedCategoryIds.value = categoryIds

    // 2. 按分类加载商品
    for (const catId of categoryIds) {
      await fetchCommodities(catId)
      const relatedGoods = list.filter(r => r.parentId === catId).map(r => r.bizId)
      selectedCommodityIds[catId] = relatedGoods
    }

    MessagePlugin.success('已加载组件关联数据')
  } catch (e) {
    console.error(e)
    MessagePlugin.error('加载关联数据失败')
  }
}

// ---------------------- 保存 ----------------------
const confirmSelect = async () => {
  if (!props.pageId || !props.componentId) {
    MessagePlugin.warning('页面ID或组件ID未定义')
    return
  }

  const relations = []
  selectedCategoryIds.value.forEach(catId => {
    relations.push({
      pageId: props.pageId,
      componentId: props.componentId,
      componentType: 'category',
      bizId: catId,
      parentId: null,
      sortOrder: 0,
      status: 1
    })

    const selectedIds = selectedCommodityIds[catId] || []
    const selectedItems = commodityMap[catId].filter(c => selectedIds.includes(c.id))
    selectedItems.forEach((item, i) => {
      relations.push({
        pageId: props.pageId,
        componentId: props.componentId,
        componentType: 'commodity',
        bizId: item.id,
        parentId: catId,
        sortOrder: i + 1,
        status: 1
      })
    })
  })

  if (relations.length === 0) {
    MessagePlugin.warning('请至少选择一个分类或商品')
    return
  }

  try {
    await RelationService.saveRelations(props.pageId, props.componentId, relations)
    MessagePlugin.success('保存成功')
    visible.value = false
  } catch (e) {
    console.error(e)
    MessagePlugin.error('保存失败')
  }
}

onMounted(fetchCategories)
</script>

<style scoped>
.selector-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.category-list {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 6px;
  background: #fafafa;
}
.category-section {
  padding: 10px 0;
  border-top: 1px dashed #e5e5e5;
}
.category-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 10px;
}
.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
